import * as userApi from '@/api/user'
import { getToken, setToken, removeToken, deleteAllCookies } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  companyInfo: {},
  userInfo: {}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_COMPANYINFO: (state, companyInfo) => {
    state.companyInfo = companyInfo
  }
}

const actions = {
  // user login
  login({ commit }, { mobile, pwd, sessionId, sig, token, smsCode }) {
    return new Promise((resolve, reject) => {
      userApi.login({
        username: mobile,
        password: pwd,
        token: token,
        sessionId: sessionId,
        sig: sig,
        smsCode: smsCode
      }).then(res => {
        const { code, data: token, message } = res
        if (code === 0) {
          commit('SET_TOKEN', token)
          setToken(token, {
            expires: 30
          })

          resolve()
        } else {
          reject(message)
        }
      }).catch(err => {
        if (err === '该企业未找到，或者没完成企业注册流程，请完善企业信息！') {
          router.push({ path: '/register', query: { mobile: mobile }})
        }
        reject(err)
      })
    })
  },

  async permission({ dispatch, commit }, state) {
    try {
      const [userRoles, userInfo] = await Promise.all([
        userApi.get_user_roles(),
        userApi.get_user_info()
      ])

      const roles = userRoles.data.reduce((init, cur) => {
        init.push(cur.roleKey)
        return init
      }, [])

      const roleNames = userRoles.data.reduce((init, cur) => {
        init.push(cur.roleName)
        return init
      }, [])
      const user = userInfo.data
      if (!roles.length) {
        roles.push('visitor')
      }
      if (!user.avatar) {
        user.avatar = '/images/avatar.gif'
      }
      user.roles = roles
      user.roleNames = roleNames
      commit('SET_ROLES', roles)
      commit('SET_USERINFO', user)
    } catch (error) {
      throw new Error(error)
    }
  },

  async updateOperator({ dispatch, commit }, state) {
    try {
      const userInfo = await userApi.get_user_info()
      const user = userInfo.data

      commit('SET_USERINFO', user)
    } catch (error) {
      throw new Error(error)
    }
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_ALLROLES', [])
      removeToken()
      resetRouter()
      // 本地记录是否导航
      let flag = null
      if (JSON.parse(localStorage.getItem('first-Flag')) === 0) {
        flag = JSON.parse(localStorage.getItem('first-Flag'))
      }
      sessionStorage.clear()
      localStorage.clear()
      deleteAllCookies()
      if (flag === 0) {
        localStorage.setItem('first-Flag', flag)
      }
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
